/*****************************************************************************
 * boer
 *****************************************************************************
 * CommomUtil.java
 *----------------------------------------------------------------------------
 * 版权HeartArea所有，联系ding_cuiping@163.com
 *----------------------------------------------------------------------------
 * Version    Date       By            Comment
 * 1.0        2014-3-20    Poppy       新建
 *****************************************************************************/
package net.heartarea.boer.util;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.heartarea.boer.apps.weixin.pojo.TextMsgBean;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.thoughtworks.xstream.XStream;

/**
 * 工具类
 * 
 * @author Poppy
 * @date 2014-3-20
 * @since 1.0
 */
public class CommonUtil {

	/**
	 * 解析xml请求
	 * 
	 * @author Poppy
	 * @date 2014-3-19
	 * @param request
	 * @return
	 * @throws Exception
	 * @since 1.0
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, String> analysisXml(HttpServletRequest request)
			throws Exception {
		// 定义返回结果
		Map<String, String> map = new HashMap<String, String>();
		// 从request中取得输入流数据
		InputStream inputStream = request.getInputStream();
		// 将输入流读取成xml形式
		SAXReader reader = new SAXReader();
		Document document = reader.read(inputStream);
		// 获取xml根元素
		Element root = document.getRootElement();
		// 获取根元素的所有子节点
		List<Element> elementList = root.elements();
		// 循环所有子节点，将节点名称作为key,内容作为value，放到map中
		for (Element e : elementList)
			map.put(e.getName(), e.getText());
		// 关闭输入流
		inputStream.close();
		// 返回map
		return map;
	}

	/**
	 * 将Bean转成xml返回
	 * 
	 * @author Poppy
	 * @date 2014-3-20
	 * @param textMsgBean
	 * @return
	 * @since 1.0
	 */
	public static String textMessageToXml(TextMsgBean textMsgBean) {
		XStream xs = new XStream();
		xs.alias("xml", TextMsgBean.class);
		return xs.toXML(textMsgBean);
	}

}
